package com.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListener;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.CancellationException;

/**
 * Date: 2024/6/5 22:54
 * Author: T_log
 * Description: LeaderElectionDemo
 */
public class LeaderElectionDemo {

    public static void main(String[] args) throws InterruptedException {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", 5000, 3000, retryPolicy);

        client.start();
        System.out.println("success connect zookeeper server");

        LeaderSelector leaderSelector = new LeaderSelector(client, "/leader/selection", new LeaderSelectorListener() {
            @Override
            public void takeLeadership(CuratorFramework curatorFramework) throws Exception {
                System.out.println("通知你，你已经成为leader了.....");
                Thread.sleep(Integer.MAX_VALUE);
            }

            @Override
            public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) {
                System.out.println("通知你，可能是因为网络或者其他原因导致leader状态变化");
                if (connectionState.equals(ConnectionState.LOST)) {
                    throw new CancellationException();
                }
            }
        });

        leaderSelector.start();

        Thread.sleep(Integer.MAX_VALUE);
    }
}
